package com.android.fastride.update;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.support.v4.content.FileProvider;
import android.util.Log;

import com.android.fastride.FastRideApplication;
import com.android.fastride.model.http.entity.RxBean;
import com.android.fastride.model.http.entity.UpdateEntity;
import com.android.fastride.model.repository.UpdateApkRepository;
import com.peng.android.coremodule.utils.RxSchedulerUtils;

import java.io.File;

import cn.pedant.SweetAlert.SweetAlertDialog;
import rx.Subscriber;

/**
 * 更新管理器
 * Created by pengyuantao on 2017/9/21 15:37.
 */

public class UpdateManager {

  private static final String TAG = "UpdateManager";

  public static final int INSTANT_REQUEST_CODE = 9999;

  public static final String UPDATE_APK = UpdateApkRepository.UPDATE_APK;

  private static boolean must = false;




  /**
   * 校验更新
   * @param activity
   * @param onUpdateListener
   */
  public static void checkUpdate(Activity activity, OnUpdateListener onUpdateListener) {
    UpdateApkRepository.getUpdateInfo()
        .compose(RxSchedulerUtils.normalSchedulersTransformer())
        .subscribe(new Subscriber<UpdateEntity>() {
          @Override
          public void onCompleted() {
            Log.e(TAG, "onCompleted() called");
          }

          @Override
          public void onError(Throwable e) {
            Log.e(TAG, "onError() called with: e = [" + e + "]");
            onUpdateListener.onFailure(e);
          }

          @Override
          public void onNext(UpdateEntity updateEntity) {
            Log.e(TAG, "onNext() called with: updateEntity = [" + updateEntity + "]");
            if (updateEntity != null) {
              //判断当前的版本
              try {
                PackageInfo packageInfo = activity.getPackageManager().getPackageInfo(activity.getPackageName(), 0);
                int versionCode = packageInfo.versionCode;
                int serviceVersionCode =updateEntity.getVerCode();
                if (serviceVersionCode > versionCode) {
                  SweetAlertDialog.Builder builder = new SweetAlertDialog.Builder();
                  builder.context(activity).type(SweetAlertDialog.NORMAL_TYPE);
                  builder.titleText("有新版本啦").contentText(updateEntity.getUpdatelog());
                  builder.cancelable(false);
                  builder.cancelOnTouchOutside(false);
                  String versionName = updateEntity.getVerName();
                  String[] split = versionName.split("\\.");
                  if (split.length == 4 ) {
                    if ("1".equals(split[2])) {
                      must = true;
                      builder.cancelText("退出程序")
                          .cancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
                            @Override
                            public void onClick(SweetAlertDialog sweetAlertDialog) {
                              sweetAlertDialog.dismiss();
                              FastRideApplication.getApp().finishAllActivity();
                            }
                          });
                    } else {
                      must = false;
                      builder.cancelText("不更新")
                          .cancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
                            @Override
                            public void onClick(SweetAlertDialog sweetAlertDialog) {
                              onUpdateListener.onSuccess();
                            }
                          });
                    }
                    builder.confirmText("更新")
                        .confirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                          @Override
                          public void onClick(SweetAlertDialog sweetAlertDialog) {
                            sweetAlertDialog.dismiss();
                            SweetAlertDialog downloadDialog =  new SweetAlertDialog.Builder().context(sweetAlertDialog.getContext())
                                .cancelable(false)
                                .cancelOnTouchOutside(false)
                                .type(SweetAlertDialog.PROGRESS_TYPE_HORIZONTAL)
                                .titleText("正在下载")
                                .build();
                            downloadDialog.show();
                            //调用下载程序
                            UpdateApkRepository.downloadApk(updateEntity.getUrl())
                                .compose(RxSchedulerUtils.normalSchedulersTransformer())
                                .subscribe(new Subscriber<RxBean>() {
                                  @Override
                                  public void onCompleted() {
                                    Log.i(TAG, "onCompleted() called");

                                  }

                                  @Override
                                  public void onError(Throwable e) {
                                    e.printStackTrace();
                                    sweetAlertDialog.dismiss();
                                    onUpdateListener.onFailure(e);
                                  }

                                  @Override
                                  public void onNext(RxBean rxBean) {
                                    Log.e(TAG, "onNext() called with: rxBean = [" + rxBean + "]");
                                    if (rxBean.getIntValue() != 100) {
                                      downloadDialog.showProgressWithPercent(rxBean.getIntValue());
                                    } else {
                                      downloadDialog.dismiss();

                                      File apkFile = new File(rxBean.getStringValue());
                                      instantApk(activity,apkFile);
                                    }
                                  }
                                });
                          }
                        });
                    builder.build().show();
                  }
                }
              } catch (PackageManager.NameNotFoundException e) {
                e.printStackTrace();
              }
            } else {
              onUpdateListener.onFailure(new NullPointerException("update entity is null"));
            }
          }
        });
  }

  /**
   * 安装apk文件
   */
  public static void instantApk(Activity activity, File apkFile) {
    Intent intent = new Intent(Intent.ACTION_VIEW);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
      intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
      Uri contentUri = FileProvider.getUriForFile(FastRideApplication.getApp(),
          "com.android.fastride.fileprovider", apkFile);
      intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
    } else {
      intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
      intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    }
    activity.startActivityForResult(intent, INSTANT_REQUEST_CODE);
  }

  public static boolean isMust(){
    return must;
  }

}
